﻿#include "WidgetQrCode.h"

WidgetQrCode::WidgetQrCode(QWidget *parent) :
    QWidget(parent)
{
    setFixedSize(146, 146);
    labelQrCode = new QLabel(this);
    labelQrCode->move(0, 0);
    labelQrCode->resize(146, 146);

}
void WidgetQrCode::onHandleQrCodeValue(QString value)
{
    m_QrCodeNum = value;
    update();//会导致一次paintEvent事件
}
void WidgetQrCode::paintEvent(QPaintEvent *)
{
    //QR_ECLEVEL_Q 容错等级
    qDebug() << "二维码的绘制中: " << m_QrCodeNum;
#if ( PRODUCER == 0 )
    QString urlInfo = "http://app.stage.duduchong.com/pl/" + m_QrCodeNum;
#elif ( PRODUCER == 1 )
    QString urlInfo = m_QrCodeNum;
#elif ( PRODUCER == 2 )
    QString urlInfo = m_QrCodeNum;
#elif ( PRODUCER == 3 || PRODUCER == 5 || PRODUCER == 6)
    QString urlInfo = m_QrCodeNum;
#elif ( PRODUCER == 4 )
    QString urlInfo = m_QrCodeNum;
#endif
    qDebug() << "二维码的绘制中: " << urlInfo;
    if( !urlInfo.isEmpty() )
    {
        qrcode = QRcode_encodeString(urlInfo.toLocal8Bit().constData(), 2, QR_ECLEVEL_H, QR_MODE_8, 1);

        qint32 temp_width=labelQrCode->width(); //二维码图片的大小
        qint32 temp_height=labelQrCode->height();

        qint32 qrcode_width = qrcode->width > 0 ? qrcode->width : 1;
        double scale_x = (double)temp_width / (double)qrcode_width; //二维码图片的缩放比例
        double scale_y =(double) temp_height /(double) qrcode_width;
        QPainter painter(this);
        QColor background(Qt::white);
        painter.setBrush(background);
        painter.setPen(Qt::NoPen);
        painter.drawRect(0, 0, temp_width, temp_height);
        QColor foreground(Qt::black);
        painter.setBrush(foreground);
        for( qint32 y = 0; y < qrcode_width; y ++)
        {
            for(qint32 x = 0; x < qrcode_width; x++)
            {
                unsigned char b = qrcode->data[y * qrcode_width + x];
                if(b & 0x01)
                {
                    QRectF r((x * scale_x), (y * scale_y), scale_x, scale_y);
                    painter.drawRects(&r, 1);
                }
            }
        }
    }
    else
    {
        qDebug() << QString("绘制二维码失败!!!");
    }
}
WidgetQrCode::~WidgetQrCode()
{
    if(qrcode != NULL)
    {
       QRcode_free(qrcode);
    }
}
